<template>
    <div class="w750 position-relative" :class="themes.theme">
        <!-- 下拉刷新组件 -->
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
            <!-- 个人信息 -->
            <div class="my-info">
                <div class="my-info-bg mb-4" style="height: 160px">
                    <img :src="themes.myBackgroundImg ? photoServer + themeBgimg : themeBgimg" alt srcset class="bg-img" />
                    <div class="info-item">
                        <div class="my-img" @click="goAccount" v-if="myInfo.headPortrait">
                            <img :src="photoServer + myInfo.headPortrait" alt />
                        </div>
                        <div class="my-img" @click="goAccount" v-else>
                            <img src="../../assets/images/head-default.png" alt />
                        </div>
                        <div class="my-mes">
                            <p class="mem-name">{{ myInfo.nickName }}</p>
                        </div>
                    </div>
                </div>
                <span class="my-account" @click="goAccount">
                    <img src="../../assets/images/set.png" alt />
                    设置
                </span>
            </div>

            <div class="position-absolute w-100" style="top: 130px">
                <!-- 个人服务 -->
                <div class="rounded-10 bg-fff" style="margin: 0 12px 10px; border-radius: 12px">
                    <div class="d-flex py-1 font-12">
                        <div class="flex-1 text-center border-line" @click="toBalance">
                            <div class="font-weight">{{ myInfo.balance || 0 }}</div>
                            <div class="mt text-999">余额</div>
                        </div>
                        <div class="flex-1 text-center border-line" @click="$toPage('/myIntegral')">
                            <div class="font-weight">{{ myInfo.integral || 0 }}</div>
                            <div class="mt text-999">{{ integralName }}</div>
                        </div>
                        <div class="flex-1 text-center" @click="goPath({ path: 'myCoupon' })">
                            <div class="font-weight">{{ myInfo.coupon || 0 }}</div>
                            <div class="mt text-999">优惠券</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 手机号码  -->
            <div class="binding-phone" v-if="!bindPhone.already">
                <div class="content">
                    <div class="text">绑定手机号,同步全渠道订单和优惠券</div>
                    <div class="bind">
                        <span class="btn" @click="showBindPhonePopup">立即绑定</span>
                    </div>
                </div>
            </div>

            <!-- 我的订单 -->
            <div class="my-order">
                <div class="entry-con" @click="goOrderList(' ')">
                    <div class="con-box">
                        <div class="fl"><span class="entry-name" style="font-weight: bold">我的订单</span></div>
                        <div class="fr" style="display: flex; justify-content: center; align-items: center">
                            <span class="entry-name" style="font-size: 12px; color: #999">全部订单</span>
                            <em class="arr" style="width: 8px; height: 8px; margin-top: 0px"><img src="@/assets/images/arrow.png" alt /></em>
                        </div>
                    </div>
                </div>
                <div class="quick-entry">
                    <dl class="item" @click="goOrderList(1)">
                        <dt class="item-img">
                            <img src="@/assets/images/pay.png" alt />
                        </dt>
                        <dd class="item-txt">待付款</dd>
                        <dd class="sub" v-if="orderNum.payment > 0">{{ orderNum.payment >= 100 ? '99+' : orderNum.payment }}</dd>
                    </dl>
                    <dl class="item" @click="goOrderList(2)">
                        <dt class="item-img">
                            <img src="../../assets/images/take-delivery.png" alt />
                        </dt>
                        <dd class="item-txt">待发货</dd>
                        <dd class="sub" v-if="orderNum.paid > 0">{{ orderNum.paid >= 100 ? '99+' : orderNum.paid }}</dd>
                    </dl>
                    <dl class="item" @click="goOrderList(3)">
                        <dt class="item-img">
                            <img src="../../assets/images/delivery.png" alt />
                        </dt>
                        <dd class="item-txt">待收货</dd>
                        <dd class="sub" v-if="orderNum.shipped > 0">{{ orderNum.shipped >= 100 ? '99+' : orderNum.shipped }}</dd>
                    </dl>
                    <dl class="item" v-if="groupStatus" @click="goOrderList(0)">
                        <dt class="item-img">
                            <img src="../../assets/images/wait-group.png" alt />
                        </dt>
                        <dd class="item-txt">待成团</dd>
                        <dd class="sub" v-if="orderNum.mergeGroup > 0">{{ orderNum.mergeGroup >= 100 ? '99+' : orderNum.mergeGroup }}</dd>
                    </dl>
                    <dl class="item" @click="goRetrueList">
                        <dt class="item-img">
                            <img src="../../assets/images/return.png" alt />
                        </dt>
                        <dd class="item-txt">退款/售后</dd>
                    </dl>
                </div>
            </div>

            <div style="padding: 0 12px">
                <div class="other-handle">
                    <div class="typeTitle">
                        <div class="title">工具与服务</div>
                        <div class="more">
                            <span class="more-text" @click="goMore">查看更多</span>
                            <div class="arr">
                                <img src="../../assets/images/arrow.png" />
                            </div>
                        </div>
                    </div>

                    <div class="type-list">
                        <dl
                            class="handle-item"
                            @click="goPath(item)"
                            v-for="(item, index) in valueAddedService"
                            :key="index"
                            v-if="item.status == true"
                        >
                            <dt class="item-img"><img :src="item.img" alt /></dt>
                            <dd class="item-txt">{{ item.serviceName }}</dd>
                        </dl>
                    </div>
                </div>
            </div>

            <!-- 猜你喜欢 -->
            <div class="guess" v-if="recommend.display">
                <div class="con-box">
                    <div class="youlike">
                        <!-- <img src="@/assets/images/youlike1.png" alt="" class="youlike1" /> -->
                        <div class="entry-name mt-1">{{ recommend.name }}</div>
                        <!-- <img src="@/assets/images/youlike2.png" alt="" class="youlike2" /> -->
                    </div>
                </div>

                <!-- 横向列表 -->
                <div class="pro-list" id="list02" style="background: #f6f7f8">
                    <ProList
                        @myEvent="goProdDetail"
                        :parmas="item"
                        :pic="item.pic"
                        :name="item.name"
                        :money="item.price"
                        v-for="(item, index) in recommendProds"
                        :key="index"
                    ></ProList>
                </div>
            </div>

            <bind-phone :bindPhone="bindPhone" ref="bindPhone" />
            <!-- 版权 -->
            <copyrightInfo />
            <div style="height: 60px"></div>
        </van-pull-refresh>
    </div>
</template>
<script>
import { mapState } from 'vuex'
import ProList from 'components/proList/proList'
import bindPhone from 'components/bindPhone/bindPhone'
import copyrightInfo from 'components/copyrightInfo/copyrightInfo'
import { getMyHome, getBadgeCount, getProdList, getValueAddedService } from 'api/my'
import { applyPromoter } from 'api/extensionApi'
import { sendSMSCode } from 'api/common/common'
import oauthApi from 'api/login'
import { disSMPointVerification } from '@/api/distributorPoints'

export default {
    components: {
        ProList,
        copyrightInfo,
        bindPhone
    },
    data() {
        return {
            isLoading: false,
            myInfo: '', //个人中心数据
            photoServer: this.$imgUrlHead,
            orderNum: {
                //订单角标数量
                payment: 0, // 待付款
                paid: 0, //已付款(待发货)
                shipped: 0, //待收货
                completed: 0, //已完成
                mergeGroup: 0, //待成团
                collects: 0, //已收藏商品数量
                msgs: 0, //未读消息数量
                tracks: 0 //足迹
            },
            themeBgimg: '',

            // 绑定手机号相关
            bindPhone: {
                already: false, // 是否已绑定
                showPopup: false
            },

            // 推荐商品
            recommend: {
                display: false,
                name: '猜你喜欢'
            },
            recommendProds: null,
            valueAddedService: [], //页面上使用
            valueAddedServiceArr: [
                {
                    id: 0,
                    serviceCode: 'ordinary',
                    serviceName: '领券中心',
                    path: '/walletModules/recCenter/recCenter',
                    img: require('@/assets/images/other08.png'),
                    status: true
                },
                {
                    id: 3,
                    serviceCode: 'ordinary',
                    serviceName: '我的收藏',
                    path: '/collection',
                    img: require('@/assets/images/collect.png'),
                    status: true
                },
                {
                    id: 4,
                    serviceCode: 'ordinary',
                    serviceName: '我的消息',
                    path: '/message',
                    img: require('@/assets/images/my-message.png'),
                    status: true
                },
                {
                    id: 5,
                    serviceCode: 'ordinary',
                    serviceName: '收货地址',
                    path: '/addressList',
                    img: require('@/assets/images/address.png'),
                    status: true
                }
                // {
                //     id: 6,
                //     serviceCode: 'ordinary',
                //     serviceName: '自提点管理',
                //     path: '/pointIndex',
                //     img: require('@/assets/images/questionnaire.png'),
                //     status: true
                // }
            ],

            groupStatus: false // 拼团活动状态
        }
    },
    computed: {
        ...mapState(['themes', 'integralName'])
    },
    mounted() {
        this.bindCode()
		if(this.$utils.test.isEmpty(this.themes)) {
			// await this.$store.dispatch('getBaseSetting')
			this.getData()
		} else {
			this._applyStyle()
		}
        this.loadValueAddedService()
    },
    activated() {
        this.loadMyHome()
    },
    methods: {
		// 获取装修楼层数据
		async getData() {
			// await this.$store.dispatch('getBaseSetting')
			// console.log(this.themes, 666666)
			// this._applyStyle()
			this.$store.dispatch('getBaseSetting').then(res => {
				if (res) {
					this._applyStyle()
					// console.log(this.floorArr)
				}
			}).catch((err) => {
				console.log(err)
			})
		},
        //应用主题
        _applyStyle() {
            // 个人中心背景图片
            let bgImg = this.themes.myBackgroundImg
            if (!bgImg) {
                let themeColor = this.themes.theme //用颜色名字来区分
                let themeBgimg = {
                    black: require('@/assets/style-images/mybg-black.png'), //黑色主题
                    green: require('@/assets/style-images/mybg-green.png'), //绿色
                    crimson: require('@/assets/style-images/mybg-crimson.png'), //红色带点粉
                    red: require('@/assets/style-images/mybg-red.png'), //红色
                    'pale-red': require('@/assets/style-images/mybg-pale-red.png'), //粉红色
                    orange: require('@/assets/style-images/mybg-orange.png'), //橘子色
                    brown: require('@/assets/style-images/mybg-brown.png'), //牛屎色
                    blue: require('@/assets/style-images/mybg-blue.png'), //蓝色
                    'light-green': require('@/assets/style-images/mybg-light-green.png') //浅绿色
                }
                this.themeBgimg = themeBgimg[themeColor]
            } else {
                this.themeBgimg = bgImg
            }

            // 读取推荐商品设置
            this.recommend = this.themes.recommendProd
            // 如果有显示推荐商品列表， 则查询推荐商品数据
            if (this.recommend.display) {
                this.recommend.name = this.recommend.name ? this.recommend.name : '猜你喜欢'
                this.loadRecomendProds()
            }
        },

        //用户信息
        async loadMyHome() {
            try {
                let { result, status, msg } = await getMyHome()
                if (status != 1) {
                    this.$toast(msg)
                    return
                }
                this.bindPhone.already = result.phone ? true : false
                this.myInfo = result
                this.$store.commit('SET_USERINFO', result)
            } catch (error) {
            }
            this.loadBadgeCount()

            let index = this.valueAddedServiceArr.findIndex((v) => {
                return v.serviceCode == 'integral'
            })
        },

        // 角标
        async loadBadgeCount() {
            try {
                let { result, status, msg } = await getBadgeCount()
                if (status != 1) {
                    this.$toast(msg)
                    return
                }
                this.orderNum = {}
                this.orderNum.collects = result.collects
                this.orderNum.msgs = result.msgs
                this.orderNum.tracks = result.tracks

                let subCounts = result.subCounts
                let map = {}
                let subCountMap = {
                    1: 'payment', //带付款
                    2: 'paid', //代发货
                    3: 'shipped', // 待收货
                    4: 'completed', //已完成,
                    0: 'mergeGroup' //待成团
                }

                subCounts.map((item) => {
                    if (item.activeType == 'MERGE_GROUP' && item.status == 2) {
                        item.status = 0
                    }
                    map[item.status] = item
                })

                for (const key in map) {
                    const element = map[key]
                    this.$set(this.orderNum, subCountMap[element.status], element.subCounts)
                }
            } catch (error) {
            }
        },

        //获取可用增值服务
        loadValueAddedService() {
            let that = this
            let newArr = this.valueAddedServiceArr.slice(0, this.valueAddedServiceArr.length)

            getValueAddedService()
                .then((res) => {
                    if (res.status == 1) {
                        let result = res.data
                        let resultFilter = result.filter((item) => {
                            return (
                                item.serviceCode == 'PROMOTERS' ||
                                item.serviceCode == 'MERGE_GROUP' ||
                                item.serviceCode == 'WARRANTY_CARD' ||
                                item.serviceCode == 'DEDICATED_SERVICE' ||
                                item.serviceCode == 'GROUP_CUSTOM' ||
                                item.serviceCode == 'PUBLISH_ARTICLE_SETTING' ||
                                item.serviceCode == 'QUESTIONNAIRE' ||
                                item.serviceCode == 'DISTRIBUTOR_SINCE_MENTION_POINT_SWITCH' 
								//||
								//item.serviceCode == 'JD_PROD_ONLINE_SETTING'
                            )
                        })

                        let valueArr = []
                        resultFilter.forEach((item) => {
                            let obj = {}
                            switch (item.serviceCode) {
                                case 'PROMOTERS':
                                    obj.path = '/applyExtension'
                                    obj.img = require('@/assets/images/other02.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break

                                case 'MERGE_GROUP':
                                    obj.path = '/pages/fight/fight'
                                    obj.img = require('@/assets/images/fight-icon.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    this.groupStatus = item.status
                                    break

                                case 'WARRANTY_CARD':
                                    obj.path = '/warrantyList'
                                    obj.img = require('@/assets/images/my-warranty-card.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break
                                case 'DEDICATED_SERVICE':
                                    obj.path = '/uniqueService'
                                    obj.img = require('@/assets/images/unique-service.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break
                                case 'GROUP_CUSTOM':
                                    obj.path = '/groupBuy'
                                    obj.img = require('@/assets/images/group-bug.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break
                                case 'PUBLISH_ARTICLE_SETTING':
                                    obj.path = '/contentCenter'
                                    obj.img = require('@/assets/images/content-center.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break
                                case 'QUESTIONNAIRE':
                                    obj.path = '/questionnaireList'
                                    obj.img = require('@/assets/images/questionnaire.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break
                                case 'DISTRIBUTOR_SINCE_MENTION_POINT_SWITCH':
                                    obj.path = '/pointIndex'
                                    obj.img = require('@/assets/images/point.png')
                                    obj.status = item.status
                                    obj.serviceName = item.serviceName
                                    break
								//case 'JD_PROD_ONLINE_SETTING':
								//    obj.path = '/onshelf'
								//    obj.img = require('@/assets/images/onshelf.png')
								//    obj.status = item.status
								//    obj.serviceName = item.serviceName
								//    break	
                            }
                            valueArr.push(obj)
                        })
                        let index = 0
                        for (const key in valueArr) {
                            const element = valueArr[key]
                            newArr.splice(index, 0, element)
                            index++
                        }
                        this.valueAddedService = newArr
                    } else {
                        this.valueAddedService = this.valueAddedServiceArr
                        that.$toast(res.msg)
                    }
                })
                .catch((e) => {
                    this.valueAddedService = this.valueAddedServiceArr
                })
        },

        // 加载推荐商品列表
        async loadRecomendProds() {
            let that = this

            try {
                let parmas = {
                    displayCount: that.recommend.displayCount,
                    source: that.recommend.prodSetting,
                    prodGroupId: that.recommend.prodGroupId
                }
                let res = await getProdList(parmas)

                if (res.status != 1) {
                    this.$toast(res.msg)
                    return
                }
                this.recommendProds = res.result
            } catch (error) {
            }
        },

        goback() {
            this.$router.back()
            this.$router.isBack = true
        },

        onRefresh() {
            let that = this
            setTimeout(() => {
                this.$store.dispatch('getBaseSetting')

                that._applyStyle()
                that.loadValueAddedService()

                that.loadMyHome()
                    .then(() => {})
                    .finally(() => {
                        that.isLoading = false
                        this.$toast({ message: '刷新完成' })
                    })
            }, 1000)
        },

        // 前往账户设置
        goAccount() {
            this.$router.push('/account')
        },

        // 前往订单列表
        goOrderList(status) {
            sessionStorage.setItem('status', status)
            this.$router.push('/orderList')
        },

        // 去售后列表
        goRetrueList() {
            this.$router.push('/returnList')
        },

        //去增值服务的页面
        goPath(item) {
            if (item.path == '/pointIndex') {
                this.checkPointStatus(item)
                return
            }
            this.$router.push(item.path)
        },

        // 判断分享员自提点状态
        checkPointStatus(item) {
            disSMPointVerification()
                .then((res) => {
                    if (!res.success) {
                        return void this.$toast(res.msg)
                    }

                    const statusList = ['PASS', 'CLOSE_APPLY', 'REJECT_CLOSE', 'BAN']

                    if (statusList.includes(res.result)) {
                        this.$router.push('pointList')
                    } else {
                        this.$router.push(item.path)
                    }
                })
                .catch((err) => {
                })
        },

        // 前往商品详情
        goProdDetail(event) {
            let prodId = event.prodId
            this.$router.push({
                path: `/goodsDetail`,
                query: {
                    goodsInfoId: prodId
                }
            })
        },

        // 弹出绑定手机弹出
        showBindPhonePopup() {
            // this.bindPhone.showPopup = true
			// this.$router.replace({ path: '/login', query: { redirect: this.$route.fullPath } })
			this.$utils.goLoginPage(this)
        },

        //去更多
        goMore() {
            this.$toast('此功能暂未开放，敬请期待')
        },

        // 去余额页面
        toBalance() {
            if (!this.myInfo.hasBalance) {
                return
            }
            this.$router.push({ name: 'balance' })
        },

        // 判断是不是有绑定qrCode
        bindCode() {
            const qrCode = sessionStorage.getItem('qrCode')
            if (qrCode) {
                oauthApi
                    .bindRelationshipByQRCode({
                        qrCodeNumber: qrCode
                    })
                    .then((res) => {
                        if (!res.success) {
                            // this.$toast(res.msg)     // 错误信息提示，暂时无用先屏蔽
                            return
                        }
                        sessionStorage.removeItem('qrCode')
                    })
                    .catch((err) => {
                        sessionStorage.removeItem('qrCode')
                    })
            }
        },
    }
}
</script>

<style src="@/assets/css/popup.css" scoped></style>
<style src="@/assets/css/my.css" scoped></style>
<style src="@/assets/css/style/my-style.css" scoped></style>
<style lang="stylus" scoped>
.entry-con .con-box {
  border-bottom: none;
}
.my-order {
  padding: 0 12px;
  .entry-con {
    border-radius: 12px 12px 0 0;
  }

  .quick-entry {
    border-radius: 0 0 12px 12px;
  }
}

.other-handle {
  border-radius: 12px;

  .type-list {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .typeTitle {
    display: flex;
    margin-bottom: 5px;
    padding: 0 0px 10px 0px;
    width: 100%;

    .title {
      flex: 1;
      font-size: 14px;
      font-weight: bold;
    }

    .more {
      display: flex;
      margin-left: auto;
      color: #999;
      font-size: 14px;
      justify-content: center;
      align-items: center;
      .more-text {
        font-size: 12px;
        color: rgb(153, 153, 153);
      }
      .arr {
        width: 8px !important;
        height: 8px !important;
        margin-top: 0px !important;
        img {
          width: 100%;
          height: 100%;
          display: inline-block;
          vertical-align: top;
        }
      }
    }
  }
}

.border-line {
    position: relative;
    &::after {
        content: '';
        position: absolute;
        top: 25%;
        right: 0;
        width: 1px;
        height: 20px;
        background: #f2f2f2;
    }
}
</style>
